import React, { useState, useEffect, useRef } from 'react';
import { Select, Tag, Space, Avatar, Tooltip, message } from 'antd';
import { UserOutlined, MailOutlined, CloseOutlined } from '@ant-design/icons';
import { request } from '@umijs/max';
import { debounce } from 'lodash';

interface Contact {
  id: number;
  name: string;
  email: string;
  avatar?: string;
  source?: string; // 来源：数据源名称
}

interface Recipient {
  email: string;
  name?: string;
  source?: string;
}

interface SmartRecipientInputProps {
  value?: Recipient[];
  onChange?: (recipients: Recipient[]) => void;
  placeholder?: string;
  disabled?: boolean;
  maxCount?: number;
}

const SmartRecipientInput: React.FC<SmartRecipientInputProps> = ({
  value = [],
  onChange,
  placeholder = "输入姓名或邮箱地址，回车添加",
  disabled = false,
  maxCount,
}) => {
  const [searchValue, setSearchValue] = useState('');
  const [searchResults, setSearchResults] = useState<Contact[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const selectRef = useRef<any>(null);

  // 防抖搜索联系人
  const debouncedSearch = debounce(async (query: string) => {
    if (!query.trim()) {
      setSearchResults([]);
      return;
    }

    setLoading(true);
    try {
      // 调用后端API搜索联系人
      const response = await request('/api/contacts/search', {
        method: 'GET',
        params: { q: query, limit: 10 },
      });
      console.log('搜索联系人响应:', response);
      setSearchResults(response.contacts || []);
    } catch (error) {
      console.warn('搜索联系人失败:', error);
      setSearchResults([]);
    } finally {
      setLoading(false);
    }
  }, 300);

  useEffect(() => {
    debouncedSearch(searchValue);
  }, [searchValue]);

  // 验证邮箱格式
  const isValidEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  // 添加收件人
  const addRecipient = (recipient: Recipient) => {
    if (!recipient.email) return;

    // 检查是否已存在
    const exists = value.some(r => r.email === recipient.email);
    if (exists) {
      message.warning('该收件人已存在');
      return;
    }

    // 检查数量限制
    if (maxCount && value.length >= maxCount) {
      message.warning(`最多只能添加 ${maxCount} 个收件人`);
      return;
    }

    const newRecipients = [...value, recipient];
    onChange?.(newRecipients);
    setSearchValue('');
    setOpen(false);
  };

  // 删除收件人
  const removeRecipient = (email: string) => {
    const newRecipients = value.filter(r => r.email !== email);
    onChange?.(newRecipients);
  };

  // 处理输入
  const handleSearch = (searchText: string) => {
    setSearchValue(searchText);
    setOpen(!!searchText.trim());
  };

  // 处理选择
  const handleSelect = (selectedValue: string, option: any) => {
    if (option.isCustom) {
      // 用户直接输入的邮箱或姓名
      const input = selectedValue.trim();
      if (isValidEmail(input)) {
        addRecipient({ email: input });
      } else {
        // 可能是姓名，提示用户输入邮箱
        message.warning('请输入有效的邮箱地址');
      }
    } else {
      // 从搜索结果选择的联系人
      const contact = searchResults.find(c => c.id.toString() === selectedValue);
      if (contact) {
        addRecipient({
          email: contact.email,
          name: contact.name,
          source: contact.source,
        });
      }
    }
  };

  // 处理回车键
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && searchValue.trim()) {
      e.preventDefault();
      const input = searchValue.trim();
      if (isValidEmail(input)) {
        addRecipient({ email: input });
      } else {
        message.warning('请输入有效的邮箱地址');
      }
    }
  };

  // 渲染收件人标签
  const renderRecipientTag = (recipient: Recipient) => (
    <Tag
      key={recipient.email}
      closable
      onClose={() => removeRecipient(recipient.email)}
      style={{
        marginBottom: 4,
        padding: '4px 8px',
        borderRadius: '16px',
        display: 'flex',
        alignItems: 'center',
        maxWidth: '200px',
      }}
    >
      <Space size={4}>
        <Avatar size={16} icon={<UserOutlined />} />
        <span style={{ maxWidth: '120px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {recipient.name || recipient.email}
        </span>
        {recipient.name && (
          <Tooltip title={recipient.email}>
            <MailOutlined style={{ fontSize: '12px', color: '#999' }} />
          </Tooltip>
        )}
      </Space>
    </Tag>
  );

  // 生成选项
  const options = [
    // 搜索结果
    ...searchResults.map(contact => ({
      label: (
        <Space>
          <Avatar size={20} icon={<UserOutlined />} />
          <div>
            <div style={{ fontWeight: 500 }}>{contact.name}</div>
            <div style={{ fontSize: '12px', color: '#999' }}>{contact.email}</div>
            {contact.source && (
              <div style={{ fontSize: '11px', color: '#ccc' }}>来自: {contact.source}</div>
            )}
          </div>
        </Space>
      ),
      value: contact.id.toString(),
      isCustom: false,
    })),
    // 如果输入的是邮箱格式，显示直接添加选项
    ...(searchValue.trim() && isValidEmail(searchValue.trim()) ? [{
      label: (
        <Space>
          <MailOutlined />
          <span>添加: {searchValue.trim()}</span>
        </Space>
      ),
      value: searchValue.trim(),
      isCustom: true,
    }] : []),
  ];

  return (
    <div>
      {/* 已选择的收件人 */}
      {value.length > 0 && (
        <div style={{ marginBottom: 8, display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {value.map(renderRecipientTag)}
        </div>
      )}
      
      {/* 输入框 */}
      <Select
        ref={selectRef}
        mode="combobox"
        value={searchValue}
        placeholder={placeholder}
        disabled={disabled}
        open={open}
        onSearch={handleSearch}
        onSelect={handleSelect}
        onDropdownVisibleChange={setOpen}
        onInputKeyDown={handleKeyDown}
        loading={loading}
        options={options}
        style={{ width: '100%' }}
        dropdownStyle={{ maxHeight: 300 }}
        notFoundContent={
          searchValue.trim() ? (
            loading ? '搜索中...' : '未找到匹配的联系人'
          ) : '输入姓名或邮箱地址进行搜索'
        }
        filterOption={false}
        showSearch
        allowClear
      />
      
      {/* 统计信息 */}
      {value.length > 0 && (
        <div style={{ marginTop: 4, fontSize: '12px', color: '#999' }}>
          已添加 {value.length} 个收件人
          {maxCount && ` / ${maxCount}`}
        </div>
      )}
    </div>
  );
};

export default SmartRecipientInput;
